package com.open.capacity.controller;

import com.open.capacity.common.web.Result;
import com.open.capacity.model.BusinessData;
import com.open.capacity.model.LoginModel;
import com.open.capacity.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/login")
public class loginController {
    @Autowired
    private LoginService loginService;

    @PostMapping("/loginCheck")
    public Result loginCheck(LoginModel loginModel, HttpSession httpSession) {
        if (loginModel.getUserna().contains("@")) {
            loginModel.setEmails(loginModel.getUserna());
        } else{
            loginModel.setNumber(loginModel.getUserna());
        }
        String locode = loginModel.getLocode();
        if (!locode.equals(httpSession.getAttribute("code"))) {
            return Result.failed("验证码不正确!");
        }

        try {
            //通过邮箱或账号查询是否存在相应用户
            BusinessData businessData = loginService.login(loginModel);
            //进行校验操作，校验密码和状态
            if (businessData.getEnable() == 0) {
                return Result.failed("该用户已被禁用！");
            }
            //明文密码使用MD5加密后操作
            String passwd = DigestUtils.md5DigestAsHex(loginModel.getPasswd().getBytes());
            return passwd.equals(businessData.getPasswd()) ? Result.succeed(businessData, "操作成功！") : Result.failed("密码错误！");
        } catch (Exception e) {
            log.error("登录操作失败，请查看异常描述！", e);
        }
        return Result.failed("用户不存在或被禁用！");
    }
}
